//
//  MouthlyPlanHomePage.m
//  TimeManager2.0
//
//  Created by 刘凯敏 on 12/12/2016.
//  Copyright © 2016 刘凯敏. All rights reserved.
//

#import "MouthlyPlanHomePage.h"

//获取屏幕的高度和宽度
#define kSCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define kSCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
//日历整体宽度
#define colW (kSCREEN_WIDTH - 30)
//单元格宽度和高度
#define cellW  (colW/7)
#define cellH  (colW/7)
//页眉宽度和高度
#define headerW  colW
#define headerH  50
//日历整体高度
#define colH (6 * cellH + headerH)

@interface MouthlyPlanHomePage () <UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate>
@end

@implementation MouthlyPlanHomePage{
    NSArray *_time;
    NSArray *_detail;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    //为tableView控件设置datasource和delegate
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    //为colleView控件设置datasour和delegate
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //网格位置与大小
    self.collectionView.frame = CGRectMake(15, 70, colW, colH);
    //设置网格布局
    //创建UICollectionViewFlowLayout布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //设置页眉宽度和高度
    flowLayout.headerReferenceSize = CGSizeMake(headerW, headerH);
    //设置单元格的宽度和高度
    flowLayout.itemSize = CGSizeMake(cellW, cellH);
    //scrollDirection：用于控制UICollectionView的滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置section（分区）的上下左右空白区域的大小
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //设置单元格之间的最小行间距与最小列间距
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    self.collectionView.collectionViewLayout = flowLayout;
    
    [self loadData];
    [self addHeader];
    
    _time = @[@"7:00-8:00",@"8:00-9:00",@"9:00-10:00",@"10:00-11:00"];
    _detail = @[@"测试1",@"测试2",@"测试3",@"测试4"];
    
}

#pragma mark - 初始化数据
- (void) loadData{
    
    _date = [NSDate date];
    self.totalDayThisMonth = [self getTotalDaysThisMonth:_date];
    self.firstWeekDay = [self getWeekdayWithYear:[self year:_date] month:[self month:_date] day:1];
    if (self.firstWeekDay == 7) {
        self.lastSum = 0;
    }else{
        self.lastSum = self.firstWeekDay;
    }
    self.sumDays = self.totalDayThisMonth + self.lastSum;
}


#pragma mark - UICollectionViewDataSource

//第section有多少个格子
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.sumDays;
}

//表格实现
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dayColID" forIndexPath:indexPath];
    //表格边框样式
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
    //获取label控件
    UILabel *dayLabel = (UILabel *) [cell viewWithTag:1];
    
    if(indexPath.row >= self.lastSum){
        //本月数据展示
        dayLabel.text = [NSString stringWithFormat:@"%ld",(indexPath.row + 1 - self.lastSum)];
    }
    else dayLabel.text = nil;
    return cell;
}

//UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"didSelectItemAtIndexPath -- %ld",(long)indexPath.row);
}

//返回这个UICollectionView是否可以被选择
- (BOOL) collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void) addHeader{
    //创建一个显示当前年月的label
    self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellW, 0, 290-cellW*2, 25)];
    self.dateLabel.text = [NSString stringWithFormat:@"%ld年%.2ld月",[self year:_date],[self month:_date]];
    self.dateLabel.textAlignment = NSTextAlignmentCenter;
    [self.collectionView addSubview:self.dateLabel];
    //跳转上一个月和下一个按钮
    UIButton *lastMonth = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, cellW, 25)];
    [lastMonth setTitle:@"上一月" forState:UIControlStateNormal];
    [lastMonth setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [lastMonth setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    lastMonth.titleLabel.font = [UIFont systemFontOfSize:12];
    //没有这句按钮状态不改变
    lastMonth.selected = YES;
    //为按钮添加事件
    [lastMonth addTarget:self action:@selector(lastClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:lastMonth];
    UIButton *nextMonth = [[UIButton alloc] initWithFrame:CGRectMake(290-cellW, 0, cellW, 25)];
    [nextMonth setTitle:@"下一月" forState:UIControlStateNormal];
    [nextMonth setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [nextMonth setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    nextMonth.titleLabel.font = [UIFont systemFontOfSize:12];
    nextMonth.selected = YES;
    //为按钮添加事件
    [nextMonth addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView addSubview:nextMonth];
}

//表头实现
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *view;
    if (kind == UICollectionElementKindSectionHeader) {
        view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerIdentifier" forIndexPath:indexPath];
        //7个显示星期几的label
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, cellW, 25)];
        label1.text = @"日";
        label1.textColor = [UIColor whiteColor];
        label1.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label1.font = [UIFont systemFontOfSize:14];
        label1.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label1];
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(cellW, 25, cellW, 25)];
        label2.text = @"一";
        label2.textColor = [UIColor whiteColor];
        label2.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label2.font = [UIFont systemFontOfSize:14];
        label2.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label2];
        UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(cellW*2, 25, cellW, 25)];
        label3.text = @"二";
        label3.textColor = [UIColor whiteColor];
        label3.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label3.font = [UIFont systemFontOfSize:14];
        label3.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label3];
        UILabel *label4 = [[UILabel alloc] initWithFrame:CGRectMake(cellW*3, 25, cellW, 25)];
        label4.text = @"三";
        label4.textColor = [UIColor whiteColor];
        label4.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label4.font = [UIFont systemFontOfSize:14];
        label4.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label4];
        UILabel *label5 = [[UILabel alloc] initWithFrame:CGRectMake(cellW*4, 25, cellW, 25)];
        label5.text = @"四";
        label5.textColor = [UIColor whiteColor];
        label5.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label5.font = [UIFont systemFontOfSize:14];
        label5.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label5];
        UILabel *label6 = [[UILabel alloc] initWithFrame:CGRectMake(cellW*5, 25, cellW, 25)];
        label6.text = @"五";
        label6.textColor = [UIColor whiteColor];
        label6.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label6.font = [UIFont systemFontOfSize:14];
        label6.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label6];
        UILabel *label7 = [[UILabel alloc] initWithFrame:CGRectMake(cellW*6, 25, cellW, 25)];
        label7.text = @"六";
        label7.textColor = [UIColor whiteColor];
        label7.backgroundColor = [UIColor colorWithRed:1.00 green:0.50 blue:0.50 alpha:1.00];
        label7.font = [UIFont systemFontOfSize:14];
        label7.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label7];
    }
    return view;
}

#pragma mark - 上一月与下一月按钮点击事件
- (void) lastClick:(UIButton *) btn{
    
    NSDate *lastDate = [self lastMonth:_date];
    //更新
    _date = lastDate;
    
    self.totalDayThisMonth = [self getTotalDaysThisMonth:lastDate];
    self.firstWeekDay = [self getWeekdayWithYear:[self year:lastDate] month:[self month:lastDate] day:1];
    if (self.firstWeekDay == 7) {
        self.lastSum = 0;
    }else{
        self.lastSum = self.firstWeekDay;
    }
    self.sumDays = self.totalDayThisMonth + self.lastSum;
    
    self.dateLabel.text = [NSString stringWithFormat:@"%ld年%.2ld月",[self year:lastDate], [self month:lastDate]];
    
    [self.collectionView reloadData];
}

- (void) nextClick:(UIButton *) btn{

    NSDate *nextDate = [self nextMonth:_date];
    _date = nextDate;

    self.totalDayThisMonth = [self getTotalDaysThisMonth:nextDate];
    self.firstWeekDay = [self getWeekdayWithYear:[self year:nextDate] month:[self month:nextDate] day:1];
    if (self.firstWeekDay == 7) {
        self.lastSum = 0;
    }else{
        self.lastSum = self.firstWeekDay;
    }
    self.sumDays = self.totalDayThisMonth + self.lastSum;
    
    self.dateLabel.text = [[NSString alloc] initWithFormat:@"%ld年%.2ld月",[self year:nextDate],[self month:nextDate]];
    
    [self.collectionView reloadData];
}

#pragma mark - 获取某个日期的年月
- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}

#pragma mark - 获取下个月或上个月的NSDate
- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

#pragma mark - 获取当前月总天数NSInteger
- (NSInteger)getTotalDaysThisMonth:(NSDate *)date{
    NSRange range = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return range.length;
}

#pragma mark - 判断给定月份的天数int
- (NSInteger)getTotalDaysWithMonth:(NSInteger)month withYear:(NSInteger)year{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:month];
    [comps setYear:year];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    NSDate *date = [gregorian dateFromComponents:comps];
    NSRange days = [gregorian rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return days.length;
}

#pragma mark - 判断给定日期是周几
//返回1--周一，7--周日
- (NSInteger)getWeekdayWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:day];
    [comps setMonth:month];
    [comps setYear:year];
    
    
    NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps];
    //NSLog(@"date -- %@",date);
    NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:date];
    
    NSInteger weekDayNum = [weekdayComponents weekday] - 1;
    
    if (weekDayNum == 0) {
        weekDayNum = 7;
    }
    return weekDayNum;
}

#pragma mark - UITableViewDataSource
//该方法的返回值决定各表格行的控件
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //为表格行定义一个静态字符串作为标识符
    static NSString *cellId = @"cellId";
    //从可重用表格行队列中取出一个表格行
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    //如果取出的表格行为nil
    if(cell == nil){
        //创建自定义的cell对象
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    //从IndexPath参数中获取当前行的行号
    NSUInteger rowNo = indexPath.row;
    
    UILabel *timeField = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 100, 30)];
    //设置左对齐
    timeField.textAlignment =NSTextAlignmentLeft;
    //设置字体大小
    timeField.font = [UIFont boldSystemFontOfSize:16];
    //设置文字颜色
    timeField.textColor = [UIColor blackColor];
    [cell.contentView addSubview:timeField];
    UILabel *detailField = [[UILabel alloc] initWithFrame:CGRectMake(150, 10, 100, 30)];
    //设置右对齐
    detailField.textAlignment =NSTextAlignmentRight;
    //设置字体大小
    detailField.font = [UIFont boldSystemFontOfSize:16];
    //设置文字颜色
    detailField.textColor = [UIColor blackColor];
    [cell.contentView addSubview:detailField];
    //将表格行的边框设置为圆角
    cell.layer.cornerRadius = 6;
    cell.layer.masksToBounds = YES;
    //为表格行的tImeField、detailFiled的text赋值
    timeField.text = _time[rowNo];
    detailField.text = _detail[rowNo];
    return cell;
}

//该方法的返回值决定指定分区内包含多少个表格行
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //由于只有一个分区，直接返回_time中结合元素个数代表表格的行数
    return _time.count;
}

//该方法的返回值将作为表格行的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
@end
